package services

import (
	"encoding/json"
	"fmt"
	"huaxrobot/models"
	"strconv"
	"time"
	//"encoding/json"
	//"huaxrobot/models"
)

type PerConfResponse struct {
	InterfaceName           string         `json:"interfacename"`
	TestId					string         `json:"testid"`
}


func PerformanceAdd(Id string) string {	
	planid := strconv.FormatInt(time.Now().Unix(), 10)	

	reportId := MsRun(Id)
	go PerformanceWait(planid, reportId)
	return planid
}


func PerformanceWait(planid string, reportId string) {
	plan := models.PerformanceMs{}	
	oplan := models.PlanCase{}
	plan.Create(planid)
	oplan.Create(planid, "evicloud","performance", "test", "","","","")
	//统计job
	record := models.PlanStatistics{}
	date := time.Now().Format("2006-01-02")
	if record.Get(date).Date != date {
		record.Create(date)
		//增加job计数
		record.AddTotalCount(date)
	} else {
		record.AddTotalCount(date)
	}
	for {
		performanceStatus := MsGetStatus(reportId)
		if performanceStatus == "Completed" {
			plan.UpdateStatus(planid)
			oplan.UpdateStatus(planid)
			fmt.Println("测试完成")
			content := MsGetReport(reportId)	
			var tmpresult map[string]interface{}	
			json.Unmarshal(content, &tmpresult)
			data := tmpresult["data"].(map[string]interface {})
			maxUsers := data["maxUsers"].(string)
			avgThroughput := data["avgThroughput"].(string)
			errors := data["errors"].(string)
			avgResponseTime := data["avgResponseTime"].(string)
			responseTime90 := data["responseTime90"].(string)
			avgBandwidth := data["avgBandwidth"].(string)
			avgTransactions := data["avgTransactions"].(string)
			plan.MaxUsers = maxUsers
			plan.AvgThroughput = avgThroughput
			plan.ResponseTime90 = responseTime90
			plan.AvgBandwidth = avgBandwidth
			plan.AvgResponseTime = avgResponseTime
			plan.AvgTransactions = avgTransactions
			plan.Errors = errors
			plan.Update(planid, plan)
			//更新主表
			oplan.PlanResultUrl = "http://10.100.19.138:8081/#/performance/report/view/" + reportId		
			oplan.Update(planid, oplan)
			cost := plan.GetExectTime(planid)
			record.AddExectTime(date, cost)
			break
		} 
		fmt.Println("测试未完成，等待10s")
		time.Sleep(10 * time.Second)	
	}
}





//创建接口配置
func PerformanceConfigAdd(interfacename string, testid string) string {	
	data := models.PerformanceConfig{}
	data.InterfaceName = interfacename
	data.TestId = testid	
	data.Create(data)
	return "success"
}


//创建接口配置
func PerformanceConfigListGet() []PerConfResponse {	
	data := models.PerformanceConfig{}	
	datas := data.GetList()		
	lens := len(datas)
	resp := make([]PerConfResponse,lens)
	for i:=0;i<lens; i++{		
		resp[i].InterfaceName = datas[i].InterfaceName
		resp[i].TestId = datas[i].TestId
	}
	return resp
}